
import React, { Component } from 'react';
import {
	StyleSheet, Text, FlatList, Animated, View, Image, TouchableOpacity, Alert
} from "react-native";
import { NavigationEvents } from 'react-navigation';
import moment from 'moment';
import HTTP from '../../../utils/http';
import { API, API_GENERATE } from '../../../config/api';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import ToastUtil from '../../../utils/toast';
import navigationSeevice from '../../../components/navigation/navigationSeevice';
import Dictionary from '../../../utils/dictionary';
import { Common } from '../../../component/common/Common.js';
import { RefuseModal } from '../../../component/ModalVerifylComponent.js';
import { NewAccountHome } from '../../../components/common/newAccountHome';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { ApplyOfferCard } from '../_components/ApplyOfferCard';
import { OfferCommon } from '../_common/common';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';

const scale = GLOBAL.SCALE;
const selectIcon = require('../../../imgs/select.png')

const TAB_LIST = [
	{
		name: '多轮询报价',
		bizModel: 'M', // TODO
	}, {
		name: '单轮招标',
		bizModel: 'Z',  // TODO
	}
]

export class TransApprovalList extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '报盘成交申请审批',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center',
			}
		}
	};

	constructor(props) {
		super(props);
		this.state = {
			index: 0,
			companyIndex: 0,
			tabIndex: 0,
			tabItem: 0,
			status: 'data',
			refreshIcon: false,
			listData: [],
			itemData: {},
			totalPage: '0',
			options: [],
			choice: {},
			isModal: false,
			statusSelectText: '销售报盘'
		}
		this.reload = true; // 判断是整个页面刷新还是下拉刷新
		this.totalPage = 1;
		this.pageParams = {
			pageNo: 1,
			pageSize: 10,
			bizModel: 'M',
			winRule: 'SINGLE',
			salesType: 'S',
			corpId: ''
		}
		this.selectData = {};
		this.offerTypeData = [
			{
				dictName: '销售报盘',
				dictKey: 'S'
			},
			{
				dictName: '采购报盘',
				dictKey: 'P'
			}
		]
	}


	//初始化数据
	init = async () => {
		let options = await HTTP.POST(API_GENERATE(API.PACK_APPLY_CNT))
		if (options) {
			this.setState({
				options,
				choice: options[this.state.companyIndex] || {}
			})
		} else {
			this.setState({
				status: 'error'
			})
		}
	}

	//初始化数据
	initPage = async () => {
		const { companyIndex, options } = this.state;
		const { corpId } = options[companyIndex] || {};
		this.setState({
			status: this.reload ? 'loading' : 'data',
			refreshIcon: !this.reload && this.pageParams.pageNo == '1'
		})
		this.pageParams.corpId = corpId;
		let res = await HTTP.POST(API_GENERATE(API.LEADER_APPLY_GROUP_LIST), this.pageParams);
		if (res) {
			res = this.getRequireParams(res);
			this.setState({
				listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
				status: res.rows.length > 0 ? 'data' : 'empty',
				refreshIcon: false,
				totalPage: res.totalPage,
			})
		} else {
			this.setState({
				status: 'error'
			})
		}
	}
	// 返回值数据补充
	getRequireParams = (res) => {
		if (res.rows && res.rows.length > 0) {
			res.rows.forEach(item => {
				let packageResourceList, num
				packageResourceList = item.packageResourceList || {};
				if (item.winRule === 'ALL') {
					num = 330 * scale
				}
				else {
					num = 258 * scale
				}
				item.showItem = false;
				item.boxHeight = new Animated.Value(packageResourceList && packageResourceList.length >= 2 ? num * 2 * scale : num * scale);
				item.openHeight = 0;
				item.num = num
				if (packageResourceList && packageResourceList.length > 0) {
					item.openHeight = num * packageResourceList.length
				} else {
					item.packageResourceList = []
				}
			})
		}
		console.log(res)
		return res
	}

	loadMore = () => {
		if (this.state.totalPage > this.pageParams.pageNo) {
			this.pageParams.pageNo++;
			this.reload = false;
			this.initPage();
		}
	}

	refresh = () => {
		this.pageParams.pageNo = 1;
		if (this.state.totalPage >= this.pageParams.pageNo) {
			this.reload = false;
			this.initPage();
		}
	}

	onErrorRefresh = () => {
		this.initPage();
	}

	reloadPage = () => {
		this.pageParams.pageNo = 1;
		this.reload = true;
		this.initPage();
	}
	// 同意
	auditPress = (type, item) => {
		this.auditResult = type;
		this.remark = '';
		this.selectData = item;
		if (item.multiTask) {
			this.props.navigation.navigate('TransApprovalDetail', {
				item,
				salesType: this.pageParams.salesType,
				corpId: this.pageParams.corpId
			})
		}
		else {
			console.log(item)
			this.props.navigation.navigate('PackOfferSituation', {
				bidPackageId: this.pageParams.bizModel == 'M' ? item.bidPackageIds : item.bidPackageId,
				winRule: item.winRule,
				salesType: this.pageParams.salesType,
				applyId: item.applyIds,
				type: this.pageParams.bizModel == 'M' ? 'MULTIPLE' : 'APPROVE',
				periodNum: item.periodNum
			})

		}
	}
	//回调
	_selectCallBack = (index) => {
		this.pageParams.salesType = this.offerTypeData[index].dictKey;
		this.setState({
			index,
			isModal: false,
			statusSelectText: this.offerTypeData[index].dictName
		}, () => this.reloadPage())
	}

	//切换功能
	_toggle = (onoff) => {
		this.setState({
			isModal: onoff
		})
	}

	_approvalListItim = (data) => {
		let { listData } = this.state;
		let { salesType } = this.pageParams.salesType || {};
		return (
			<View key={data.index}>
				<ApplyOfferCard
					salesType={salesType}
					itemData={data}
					bizModel={this.pageParams.bizModel}
					listData={listData}
					renderBottomComponent={this._renderBottomComponent(data.item)}
					resetListData={(resetListData) => {
						this.setState({ listData: resetListData })
					}} />
			</View>
		)
	}

	_renderBottomComponent = (item) => {
		return (
			<View style={styles.itemDayTime}>
				<TouchableOpacity style={styles.consent} onPress={() => { this.auditPress(1, item) }}>
					<Text style={styles.consentText}>同意</Text>
				</TouchableOpacity>
				<TouchableOpacity style={styles.itemdown} onPress={() => { this.auditPress(0, item) }}>
					<Text style={styles.itemdownText}>驳回</Text>
				</TouchableOpacity>
			</View>
		)
	}

	// tab切换
	changeTab = (item) => {
		this.pageParams.bizModel = item.bizModel;
		this.reloadPage();
	}
	// tab
	_renderTabWrap() {
		const { statusSelectText } = this.state;
		return (
			<View style={styles.tabWrap}>
				{
					TAB_LIST.map((item, index) => {
						return (
							<TouchableOpacity activeOpacity={1} onPress={() => { this.changeTab(item) }} key={index}
								style={[styles.tabItem, this.pageParams.bizModel == item.bizModel ? { backgroundColor: style.color.themeColor } : { backgroundColor: 'transparent' }]}>
								<Text style={[styles.tabText, this.pageParams.bizModel == item.bizModel ? { color: '#fff' } : { color: style.color.themeColor }]}>{item.name}</Text>
							</TouchableOpacity>
						)
					})
				}
				<TouchableOpacity style={styles.statusSelect} onPress={() => {
					this.setState({ isModal: true })
				}}>
					<Text style={styles.statusSelectText}>{statusSelectText}</Text>
					<Image style={styles.statusSelectIcon} source={selectIcon} />
				</TouchableOpacity>
			</View>
		)
	}

	render() {
		let { listData, refreshIcon, status, showRejectModal, choice, options, index, statusSelectText, isModal } = this.state;
		return (
			<View style={styles.container}>
				<NavigationEvents onWillFocus={async () => {
					await this.init();
					await this.initPage();
				}} />
				{options.length > 1 ?
					<NewAccountHome
						fn={(val) => {
							this.setState({ companyIndex: val }, async () => {
								this.pageParams.pageNo = 1;
								await this.init();
								await this.initPage();
							})
						}}
						options={options}
						choice={choice} />
					: null}
				{this._renderTabWrap()}
				{
					status == 'data' ? (
						(
							<View style={styles.body}>
								<FlatList
									data={listData}
									renderItem={this._approvalListItim}
									refreshing={refreshIcon}
									onEndReachedThreshold={1}
									showsVerticalScrollIndicator={false}
									onRefresh={() => { this.refresh() }}
									onEndReached={() => { this.loadMore() }}
								/>
							</View>
						)
					) : (<View style={{ flex: 1 }}>
						<PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this.onErrorRefresh} />
					</View>)
				}

				<Common type="modal" demoData={(
					<Common type="listRadio" selectIndex={index} title={'报盘类型'} listData={this.offerTypeData} selectCallBack={this._selectCallBack} />
				)} isVisible={isModal} closeCallballFn={() => { this._toggle(false) }} />
			</View>
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	body: {
		flex: 1,
		backgroundColor: style.color.bgGray
	},
	itemBorder: {
		height: 1 * scale,
		backgroundColor: '#E3E7F0',
		marginBottom: 15 * scale,
	},
	arrowIcon: {
		position: 'absolute',
		right: 0,
		top: 2 * scale,
		right: 32 * scale,
	},
	textRow: {
		marginBottom: 20 * scale
	},
	textRowText: {
		paddingLeft: 15 * scale
	},
	statusSelect: {
		backgroundColor: style.color.gray,
		opacity: 0.7,
		// marginTop: 20 * scale,
		// marginBottom: 8 * scale,
		marginLeft: 20 * scale,
		padding: 6 * scale,
		width: 94 * scale,
		borderRadius: 20 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center'
	},
	statusSelectText: {
		fontSize: 13 * scale,
		marginRight: 4 * scale
	},
	statusSelectIcon: {
		width: 12 * scale,
		height: 6 * scale,
		tintColor: "#000"
	},
	consent: {
		paddingRight: 20 * scale,
		paddingLeft: 20 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		borderWidth: 1 * scale,
		borderStyle: 'solid',
		borderColor: style.color.themeColor,
		borderRadius: 15 * scale,
		backgroundColor: style.color.themeColor,
		overflow: 'hidden'
	},
	consentText: {
		fontSize: 12 * scale,
		color: '#ffffff',
	},
	itemdown: {
		paddingRight: 20 * scale,
		paddingLeft: 20 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		borderWidth: 1 * scale,
		borderStyle: 'solid',
		borderColor: style.color.themeColor,
		borderRadius: 15 * scale,
		marginRight: 20 * scale,
		marginLeft: 10 * scale,
	},
	itemdownText: {
		fontSize: 12 * scale,
		color: style.color.themeColor,
	},
	itemDayTime: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'flex-end',
		paddingLeft: 12 * scale,
		borderTopWidth: 1 * scale,
		borderTopColor: '#E3E7F0',
		height: 50 * scale,
	},
	itemCommonText: {
		fontSize: 12 * scale,
		marginBottom: 4 * scale
	},
	tabItem: {
		paddingTop: 5 * scale,
		paddingBottom: 5 * scale,
		paddingLeft: 16 * scale,
		paddingRight: 16 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		marginHorizontal: 10,
		borderWidth: 1,
		borderRadius: 20,
		borderColor: style.color.themeColor
	},
	tabText: {
		color: '#fff'
	},
	tabWrap: {
		backgroundColor: style.color.bgGray,
		flexDirection: 'row',
		alignItems: 'center',
		paddingTop: 15 * scale,
		paddingBottom: 10 * scale
	},
})